package com.DaMie.ssmschoolshop.controller.front;


import com.DaMie.ssmschoolshop.entity.*;
import com.DaMie.ssmschoolshop.service.CommentService;
import com.DaMie.ssmschoolshop.service.GoodsService;
import com.DaMie.ssmschoolshop.service.UserService;
import com.DaMie.ssmschoolshop.util.Msg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/info/comments")
    public String showComment(@RequestParam(value = "page" , defaultValue = "1")Integer pn, HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        //一页显示几个数据
        PageHelper.startPage(pn, 15);

        CommentExample commentExample = new CommentExample();
        commentExample.or().andUseridEqualTo(user.getUserid());

        //获取商品名
        List<Comment> commentList = commentService.selectByExample(commentExample);
        for (int i = 0;i<commentList.size();i++){
            Comment comment = commentList.get(i);
            Goods commentGoods = goodsService.selectByPrimaryKey(comment.getGoodsid());
            comment.setGoodsname(commentGoods.getGoodsname());
            commentList.set(i,comment);
        }

        //显示几个页号
        PageInfo page = new PageInfo(commentList,5);
        model.addAttribute("pageInfo", page);

        return "comments";
    }
    //删除评论
    @RequestMapping("/deletecomment")
    @ResponseBody
    public Msg deleteComment(Comment comment) {
        commentService.deleteByPrimaryKey(comment.getCommentid());
        return Msg.success("删除成功");
    }

    //更新评论
    @RequestMapping("/updatecomment")
    @ResponseBody
    public Msg updateComment(Comment comment,HttpServletRequest request) {
        HttpSession session=request.getSession();
        User user=(User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail("评论失败2");
        }
        comment.setUserid(user.getUserid());
        Date date=new Date();
        comment.setCommenttime(date);
        commentService.updateByPrimaryKey(comment);
        return Msg.success("更新成功");
    }
}
